<template>
   
    <n-grid>
        <!-- <n-gi :span="4">
            <n-tree :data="treeData"
                key-field="c_id"
                label-field="c_name"
                :node-props="nodeProps">

            </n-tree>
        </n-gi> -->
        <n-gi :span="24">
            <n-grid y-gap="2" :cols="24">
                <n-gi :span="24" style="padding-left: 2px;">
                    <n-space>
                        <n-button type="info" size="small" @click="editDlgVisible = true">添加</n-button>
                        <!-- <n-button type="default" size="small" @click="adminClassDlgVisible = true">分类管理</n-button> -->
                        <n-input v-model:value="searchInput" type="text" size="small" placeholder="输入关键字" 
                            @input="getAllPass" clearable />
                        <n-button type="info" size="small" @click="test">测试store</n-button>
                        <n-button type="info" size="small" @click="test3">测试store3</n-button>
                        <n-button type="info" size="small" @click="test2">测试store2{{ count }}-{{ name }}</n-button>
                        <n-button type="info" size="small" @click="test4">测试store4</n-button>
                        <span>{{ count }}-{{ name }}-{{ user.account }}</span>
                    </n-space>
                </n-gi>
                <n-gi :span="24">
                    <n-data-table
                        :columns="createColumns"
                        :data="tableData"
                        size="small"
                        :max-height="tableHeight-130"
                        :min-height="tableHeight-130"
                        :row-props="getRowProps"
                    ></n-data-table>
                </n-gi>
                <n-gi :span="24">
                    <n-grid y-gap="1" :cols="24">
                        <n-gi :span="2" class="show-field-label">账&nbsp;&nbsp;&nbsp;&nbsp;号:</n-gi>
                        <n-gi :span="20">
                            <n-input size="small" v-model:value="selectedPassItem.item.pass_account" placeholder=""></n-input>
                        </n-gi>
                        <n-gi :span="2" style="padding-left: 5px;">
                            <n-button size="small" type="info" @click="copy('account')" :disabled="!selectedPassItem.item.pass_account">拷&nbsp;&nbsp;贝</n-button>
                        </n-gi>
                        <n-gi :span="2" class="show-field-label">密&nbsp;&nbsp;&nbsp;&nbsp;码:</n-gi>
                        <n-gi :span="20">
                            <n-input size="small" v-model:value="selectedPassItem.item.pass_password" placeholder=""></n-input>
                        </n-gi>
                        <n-gi :span="2" style="padding-left: 5px;">
                            <n-button size="small" type="info" @click="copy('password')" :disabled="!selectedPassItem.item.pass_password">拷&nbsp;&nbsp;贝</n-button>
                        </n-gi>
                        <n-gi :span="2" class="show-field-label">备&nbsp;&nbsp;&nbsp;&nbsp;注:</n-gi>
                        <n-gi :span="22">
                            <n-input type="textarea" size="small" placeholder="这里显示选中项的备注信息" 
                                :autosize="{minRows:3,maxRows:4}" v-model:value="selectedPassItem.item.pass_notes"></n-input>
                        </n-gi>
                    </n-grid>
                </n-gi>
            </n-grid>
        </n-gi>
    </n-grid>
    <n-modal 
        v-model:show="editDlgVisible" 
        preset="dialog" 
        :mask-closable="false"
        title="新增"
        :on-after-leave="closeEditDlgEnv">
        <template #header>
            <div>新增</div>
        </template>
        <div>
            <n-form
                ref="passFormRef"
                :model="passForm"
                :rules="passRules"
                label-placement="left"
                label-width="auto"
                require-mark-placement="right-hanging"
                size="small">
                <n-form-item label="账号" path="item.pass_account">
                    <n-input v-model:value="passForm.item.pass_account" maxlength="256" 
                        show-count clearable placeholder="请输入账号"/>
                </n-form-item>
                <n-form-item label="密码" path="item.pass_password">
                    <n-input v-model:value="passForm.item.pass_password" maxlength="512" show-count clearable 
                        type="textarea" :autosize="{minRows:2,maxRows:3}" placeholder="请输入密码或者点击右侧按钮生成密码"/>
                    <n-button quaternary circle type="default" @click="genPass">
                        <template #icon>
                            <n-icon><reload-circle-outline/></n-icon>
                        </template>
                    </n-button>
                    <n-button quaternary circle type="default" @click="passGenSettingDlgVisible=true">
                        <template #icon>
                            <n-icon><cog-outline /></n-icon>
                        </template>
                    </n-button>
                </n-form-item>
                <n-form-item label="备注" path="item.pass_notes">
                    <n-input 
                        v-model:value="passForm.item.pass_notes"
                        type="textarea"
                        maxlength="512"
                        :autosize="{minRows:2,maxRows:3}"
                        placeholder="在这里输入备注信息"
                    />
                </n-form-item>
                <!-- <n-form-item label="分类" path="item.c_id">
                    <n-select
                        v-model:value="passForm.item.c_id"
                        label-field="c_name"
                        value-field="c_id"
                        :options="classData"
                    />
                </n-form-item> -->
            </n-form>
        </div>
        <template #action>
            <n-space>
                <n-button type="info" size="small" @click="savePassForm">保存</n-button>
                <n-button size="small" @click="editDlgVisible = false">取消</n-button>
            </n-space>
        </template>
    </n-modal>
    <n-modal v-model:show="adminClassDlgVisible"
        preset="dialog"
        title="分类管理"
        >
        <div :style="computedCss()">
            <n-grid y-gap="2" :cols="24">
            <n-gi :span="24">
                <n-button type="info" size="small" @click="editClassDlgVisible = true">新增</n-button>
            </n-gi>
            <n-gi :span="24">
                <n-data-table
                    :columns="createClassColumns"
                    :data="treeData"
                    size="small"
                ></n-data-table>
            </n-gi>
        </n-grid>
            
        </div>
    </n-modal>
    <n-modal v-model:show="editClassDlgVisible" 
        title="分类"
        preset="dialog"
        :mask-closable="false" 
        :on-after-leave="closeEditClassDlgEnv"
        :on-after-enter="openEnv">
        
        <n-form
            ref="classFormRef"
            :model="classForm"
            :rules="classRules"
            label-placement="left"
            label-width="auto"
            require-mark-placement="right-hanging"
            size="small">
            <n-form-item label="分类名称" path="class.c_name">
                <n-input v-model:value="classForm.class.c_name" maxlength="12" show-count autofocus ref="classInput"/>
            </n-form-item>
        </n-form>
        <template #action>
            <n-space>
                <n-button type="info" size="small" @click="editClassHandle">保存</n-button>
                <n-button size="small" @click="editClassDlgVisible = false">取消</n-button>
            </n-space>
        </template>
    </n-modal>
    <n-modal v-model:show="passGenSettingDlgVisible" preset="dialog" title="生成规则配置">
        <n-form
            ref="passGenSettingFormRef"
            :model="passGenForm"
            label-placement="left"
            label-width="auto"
            require-mark-placement="right-hanging"
            size="small">
            <n-form-item label="密码长度">
                <n-slider v-model:value="passGenForm.gen.length" :step="1" :max="128" :min="1" show-tooltip/>
                <span style="width:30px;">{{ passGenForm.gen.length }}</span>
            </n-form-item>
            <n-form-item label="">
                <n-checkbox v-model:checked="passGenForm.gen.uppercaseLetter">
                    A-Z 大写字母
                </n-checkbox>
            </n-form-item>
            <n-form-item label="">
                <n-checkbox v-model:checked="passGenForm.gen.lowercaseLetters">
                    A-Z小写字母
                </n-checkbox>
            </n-form-item>
            <n-form-item label="">
                <n-checkbox v-model:checked="passGenForm.gen.number">
                    0-9 位数字
                </n-checkbox>
            </n-form-item>
            <n-form-item label="">
                <n-checkbox v-model:checked="passGenForm.gen.specialCharacters">
                    !@#$%^&*= 符号
                </n-checkbox>
            </n-form-item>
            <n-form-item label="">
                <n-checkbox v-model:checked="passGenForm.gen.exclude">
                    避免使用相似的字符 (1lIioO0)
                </n-checkbox>
            </n-form-item>
        </n-form>
        <template #action>
            <n-space>
                <n-button type="info" size="small" @click="applyGenSetting">应用</n-button>
            </n-space>
        </template>
    </n-modal>
</template>
<script setup>
import {ref,reactive,h} from 'vue';
import { useMessage,NButton,useDialog,NSpace,NText,NIcon } from "naive-ui";
import { invoke } from "@tauri-apps/api/core";
import {writeText} from '@tauri-apps/plugin-clipboard-manager';
import { CashOutline as CashIcon,CogOutline,ReloadCircleOutline,CreateOutline,TrashOutline,
    CopyOutline } from "@vicons/ionicons5";
import {useCounterStore} from '../../stores/counter';
import {useAppStore} from '../../stores/app';
import {storeToRefs} from 'pinia';


const message = useMessage();
const dialog = useDialog();

const treeData = ref([]);
const classData = ref([]);
const selectedClassId = ref('all');
const searchInput = ref('');
const tableHeight = ref(300);
const tableData = ref([]);
const editDlgVisible = ref(false);
const adminClassDlgVisible = ref(false);
const editClassDlgVisible = ref(false);
const passGenSettingDlgVisible = ref(false);
const passFormRef = ref(null);
const classFormRef = ref(null);
const passForm = ref({
    item:{
        pass_account: '',
        pass_password: '',
        pass_notes: '',
        pass_id: ''
    }
});
function handleRowClick(row){
    console.log(row.pass_account);
    selectedPassItem.value.item = {...row};
}
function getRowProps(row){
    return {
        onClick: ()=>handleRowClick(row),
    }
}
const passRules = {
    item:{
        pass_account:{
            required: true,
            trigger: ['blur','change'],
            message: "账号不能为空!"
        },
        pass_password:{
            required: true,
            trigger: ['change'],
            message: "密码不能为空!"
        }
    }
}
const classForm = ref({
    class: {
        c_id: '',
        c_name:''
    }
});
const classRules = {
    class:{
        c_name:{
            required: true,
            trigger: ['blur','change'],
            message: "分类名称不能为空!"
        }
    }
}
const passGenForm = ref({
    gen:{
        length: 12,
        uppercaseLetter: true,
        lowercaseLetters: true,
        number: true,
        specialCharacters: true,
        exclude: true
    }
})
const createColumns = ref([
    {
        title:'操作',
        key: 'pass_id',
        width: 80,
        render(row){
            return [
                h(
                    NButton,
                    {
                        quaternary:true,
                        circle:true,
                        size:'small',
                        type:'info',
                        onClick:()=>editItem(row)
                    },
                    h(NIcon,{},h(CreateOutline,{}))),
                h(
                    NButton,
                    {
                        quaternary:true,
                        circle:true,
                        size:'small',
                        type:'error',
                        onClick:()=>delItem(row)
                    },
                    h(NIcon,{},h(TrashOutline,{})))
            ]
        }
    },{
        title: '账号',
        key: 'pass_account',
        width: 200,
        ellipsis:{
            tooltip: true
        }
    },{
        title:'备注',
        key: 'pass_notes',
        ellipsis:{
            tooltip: true
        }
    }
]);
const createClassColumns = ref([
    {
        title: '分类名称',
        key: 'c_name',
    },{
        title: '操作',
        key: 'c_id',
        width: 120,
        render(row){
            if(row.c_id != 'all'){
                return [
                    h(NButton,{
                        size: 'small',
                        type: 'info',
                        style:{
                            marginRight: '3px'
                        },
                        onClick: ()=>editClass(row)
                    },{
                        default: ()=> "修改"
                    }),
                    h(NButton,{
                        size: 'small',
                        type: 'error',
                        onClick: ()=> delClass(row)
                    },{
                        default: ()=> "删除"
                    })
                ];
            }else{
                return [];
            }
            
        }
    }
]);
const selectedPassItem = ref({
    item:{...passForm.value.item}
});

const classInput = ref(null);
refreshTree();
refreshCache();
getAllPass();
getPassGenSetting();
const store = useCounterStore();
const appStore = useAppStore();

const { count,name } = storeToRefs(store);
const {user} = storeToRefs(appStore);


window.addEventListener('resize',()=>{
    computedTableHight();
});
function test(){
    console.log('test');
    store.increment();
}
function test2(){
    console.log(store.name);
    //store.$reset();

}
function test3(){
    store.$patch({
        count: store.count + 1,
        name: 'admin'+store.count
    });
}
function test4(){
    console.log(appStore.user.account);
}

tableHeight.value = window.innerHeight-80;
function computedTableHight(){
    tableHeight.value = window.innerHeight-80;
    console.log(tableHeight.value);
}
function computedCss(){
    return {'height': (window.innerHeight-200)+'px','overflow-y': 'auto'}
}
async function refreshTree(){
    //treeData.value = await invoke('get_all_pass_class');
    //classData.value = JSON.parse(JSON.stringify(treeData.value));
    // passForm.value.item.c_id = classData.value.length>0?classData.value[0].c_id:'';
    // treeData.value.unshift({
    //     c_name: '全部',
    //     c_id: 'all'
    // });
}
async function refreshCache(){
    await invoke('refresh_pass_cache');
}
function delClass(row){
    dialog.warning({
        title: '删除',
        content: '确定要删除此分类吗?若分类不为空,则该分类下的项目也会一起删除!',
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: ()=>{
            delClassHandle(row);
        }
    })
}
async function delClassHandle(row){
    let ret = await invoke('del_pass_class',{cId:row.c_id});
    if(ret){
        message.success('删除成功!');
        //refreshTree();
        getAllPass();
    }else{
        message.error("删除失败!");
    }
}
function editClass(row){
    classForm.value.class = row;
    editClassDlgVisible.value = true;
}
function editItem(row){
    passForm.value.item = {...row};
    editDlgVisible.value = true;
}
function delItem(row){
    dialog.warning({
        title: '删除',
        content: '确定要删除吗?',
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: ()=>{
            delPassHandle(row);
        }
    })
}
async function delPassHandle(row){
    console.log('确定删除...');
    let ret = await invoke('del_pass_item',{passId:row.pass_id});
    if(ret){
        message.success('删除成功!');
        getAllPass();
        resetSelectedPassItem();
    }else{
        message.error("删除失败!");
    }
}
function closeEditDlgEnv(){
    passForm.value.item.pass_account = '';
    passForm.value.item.pass_password = '';
    passForm.value.item.pass_notes = '';
    passForm.value.item.c_id = classData.value.length>0?classData.value[0].c_id:'';
}
function closeEditClassDlgEnv(){
    classForm.value.class.c_id = '';
    classForm.value.class.c_name = '';
}
function openEnv(){
    classInput.value.focus();
}
function savePassForm(e){
    e.preventDefault();
    passFormRef.value?.validate((errors)=>{
        if(errors){
            console.log(errors);
        }else{
            savePassFormHandle();
        }
    })
}
async function savePassFormHandle(){
    let ret = await invoke('save_pass_item_form',{
        passId:passForm.value.item.pass_id,
        passAccount: passForm.value.item.pass_account,
        passPassword: passForm.value.item.pass_password,
        passNotes: passForm.value.item.pass_notes
    });
    console.log(ret);
    if(ret){
        message.success('保存成功!');
        editDlgVisible.value = false;
        getAllPass();
    }else{
        message.error('保存失败!');
    }
}
async function getAllPass(){
    tableData.value = await invoke('get_all_pass',{keyWord:searchInput.value});
}
function nodeProps({option}){
    return {
        onClick(){
            console.log(option);
            selectedClassId.value = option.c_id;
            getAllPass();
        }
    }
}
async function applyGenSetting(){
    let ret = await invoke('apply_pass_gen_setting',{setting:JSON.stringify(passGenForm.value.gen)});
    if(ret){
        message.success('保存成功!');
        passGenSettingDlgVisible.value = false;
    }else{
        message.error('保存失败!');
    }
}
async function genPass(){
    let pass = await invoke('pass_gen_pass');
    passForm.value.item.pass_password = pass;
}
async function getPassGenSetting(){
    let ret = await invoke('common_get_setting_item',{sType:'pass_gen_setting'});
    
    if(ret.length>0){
        passGenForm.value.gen = JSON.parse(ret[0].s_value);
        console.log(passGenForm.value.gen);
    }
}
async function editClassHandle(){
    let ret = await invoke("save_pass_class",{cId:classForm.value.class.c_id,cName:classForm.value.class.c_name});
    if(ret){
        message.success('保存成功!');
        editClassDlgVisible.value = false;
        refreshTree();
    }else{
        message.error('保存失败!');
    }
}
async function copy(v){
    console.log(v);
    if(v == 'account'){
        await writeText(selectedPassItem.value.item.pass_account);
    }else if(v == 'password'){
        await writeText(selectedPassItem.value.item.pass_password);
    }else{
        message.error('未知的拷贝类型!');
    }
    
}
function resetSelectedPassItem(){
    selectedPassItem.value.item = {...passForm.value.item}
}
</script>
<style scoped>
.show-field-label{
    text-align: right;
    padding-right: 5px;
}
</style>